let fs = require('fs');
let path = require('path');
let Sequelize = require('sequelize');
let conf = require('../conf');
let db = {};

let mysql = new Sequelize(conf.mysql.database, conf.mysql.user, conf.mysql.password, {
  host: conf.mysql.host,
  port: conf.mysql.port,
  dialect: 'mysql',
  pool: {
    max: 10,
    min: 1,
    idle: 10000
  },
	dialectOptions: {
		charset: 'utf8mb4',
    decimalNumbers: true,
    supportBigNumbers: true,
    bigNumberStrings: false
	},
  // timezone: '+08:00',
  logging: false
  // logging: console.log
});

fs.readdirSync(__dirname)
  .filter(file => (file.indexOf('.') !== -1) && (file !== 'index.js'))
  .forEach((file) => {
    let model = require(path.join(__dirname, file))(mysql,Sequelize);
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db);
  }
});

mysql.sync();

db.mysql = mysql;
db.Sequelize = Sequelize;

module.exports = db;